using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using RabbitMQ.Client;

namespace UniversalAdminSystem.Infrastructure.RabbitMQ;

public class RabbitMqTopologyInitializer : IHostedService
{
    private readonly IConnection _conn;
    private readonly IConfiguration _cfg;
    private readonly ILogger<RabbitMqTopologyInitializer> _logger;

    public RabbitMqTopologyInitializer(IConnection conn, IConfiguration cfg, ILogger<RabbitMqTopologyInitializer> logger)
    {
        _conn = conn; _cfg = cfg; _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        using var ch = _conn.CreateModel();
        var exchange = _cfg["RabbitMq:Exchange"] ?? "file-processing";
        var queue = _cfg["RabbitMq:Queue"] ?? "file-processing-queue";
        var routingKey = _cfg["RabbitMq:RoutingKey"] ?? "file-processing";

        ch.ExchangeDeclare(exchange, type: "topic", durable: true, autoDelete: false);
        ch.QueueDeclare(queue, durable: true, exclusive: false, autoDelete: false, arguments: null);
        ch.QueueBind(queue, exchange, routingKey);

        _logger.LogInformation("RabbitMQ 拓扑已就绪: exchange={Exchange}, queue={Queue}, routingKey={RoutingKey}",
            exchange, queue, routingKey);

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
